<?php
/**
 * 标准模式公共函数库
 */

/**
 * 错误输出
 * @param mixed $error 错误
 * @return void
 */
function halt($error) {
    $e = array();
    if (APP_DEBUG) {
        //调试模式下输出错误信息
        if (!is_array($error)) {
            $trace          = debug_backtrace();
            $e['message']   = $error;
            $e['file']      = $trace[0]['file'];
            $e['class']     = isset($trace[0]['class'])?$trace[0]['class']:'';
            $e['function']  = isset($trace[0]['function'])?$trace[0]['function']:'';
            $e['line']      = $trace[0]['line'];
            $traceInfo      = '';
            $time = date('y-m-d H:i:m');
            foreach ($trace as $t) {
                $traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') ';
                $traceInfo .= $t['class'] . $t['type'] . $t['function'] . '(';
                $traceInfo .= implode(', ', $t['args']);
                $traceInfo .=')<br/>';
            }
            $e['trace']     = $traceInfo;
        } else {
            $e              = $error;
        }
    } else {
        //否则定向到错误页面
        $error_page         = C('ERROR_PAGE');
        if (!empty($error_page)) {
            redirect($error_page);
        } else {
            if (C('SHOW_ERROR_MSG'))
                $e['message'] = is_array($error) ? $error['message'] : $error;
            else
                $e['message'] = C('ERROR_MESSAGE');
        }
    }
    // 包含异常页面模板
    include C('TMPL_EXCEPTION_FILE');
    exit;
}

/**
 * 自定义异常处理
 * @param string $msg 异常消息
 * @param string $type 异常类型 默认为ShaguaException
 * @param integer $code 异常代码 默认为0
 * @return void
 */
function throw_exception($msg, $type='ShaguaException', $code=0) {
    if (class_exists($type, false))
        throw new $type($msg, $code, true);
    else
        halt($msg);        // 异常类型不存在则输出错误信息字串
}

/**
 * 浏览器友好的变量输出
 * @param mixed $var 变量
 * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
 * @param string $label 标签 默认为空
 * @param boolean $strict 是否严谨 默认为true
 * @return void|string
 */
function dump($var, $echo=true, $label=null, $strict=true) {
    $label = ($label === null) ? '' : rtrim($label) . ' ';
    if (!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        } else {
            $output = $label . print_r($var, true);
        }
    } else {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if (!extension_loaded('xdebug')) {
            $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }
    if ($echo) {
        echo($output);
        return null;
    }else
        return $output;
}

/**
 * 404处理 
 * 调试模式会抛异常 
 * 部署模式下面传入url参数可以指定跳转页面，否则发送404信息
 * @param string $msg 提示信息
 * @param string $url 跳转URL地址
 * @return void
 */
function _404($msg='',$url='') {
    APP_DEBUG && throw_exception($msg);
    if($msg && C('LOG_EXCEPTION_RECORD')) Log::write($msg);
    if(empty($url) && C('URL_404_REDIRECT')) {
        $url    =   C('URL_404_REDIRECT');
    }
    if($url) {
        redirect($url);
    }else{
        send_http_status(404);
        exit;
    }
}

/**
 * 设置当前页面的布局
 * @param string|false $layout 布局名称 为false的时候表示关闭布局
 * @return void
 */
function layout($layout) {
    if(false !== $layout) {
        // 开启布局
        C('LAYOUT_ON',true);
        if(is_string($layout)) { // 设置新的布局模板
            C('LAYOUT_NAME',$layout);
        }
    }else{// 临时关闭布局
        C('LAYOUT_ON',false);
    }
}

/**
 * URL组装 支持不同URL模式
 * @param string $url URL表达式，格式：'[分组/模块/操作#锚点@域名]?参数1=值1&参数2=值2...'
 * @param string|array $vars 传入的参数，支持数组和字符串
 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
 * @param boolean $redirect 是否跳转，如果设置为true则表示跳转到该URL地址
 * @param boolean $domain 是否显示域名
 * @return string
 */
function U($url='',$vars='',$suffix=true,$redirect=false,$domain=false) {
    // 解析URL
    $info   =  parse_url($url);
    $url    =  !empty($info['path'])?$info['path']:ACTION_NAME;
    if(isset($info['fragment'])) { // 解析锚点
        $anchor =   $info['fragment'];
        if(false !== strpos($anchor,'?')) { // 解析参数
            list($anchor,$info['query']) = explode('?',$anchor,2);
        }        
        if(false !== strpos($anchor,'@')) { // 解析域名
            list($anchor,$host)    =   explode('@',$anchor, 2);
        }
    }elseif(false !== strpos($url,'@')) { // 解析域名
        list($url,$host)    =   explode('@',$info['path'], 2);
    }
    // 解析子域名
    if(isset($host)) {
        $domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.'));
    }elseif($domain===true){
        $domain = $_SERVER['HTTP_HOST'];
        if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署
            $domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
            // '子域名'=>array('项目[/分组]');
            foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) {
                if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) {
                    $domain = $key.strstr($domain,'.'); // 生成对应子域名
                    $url    =  substr_replace($url,'',0,strlen($rule[0]));
                    break;
                }
            }
        }
    }

    // 解析参数
    if(is_string($vars)) { // aaa=1&bbb=2 转换成数组
        parse_str($vars,$vars);
    }elseif(!is_array($vars)){
        $vars = array();
    }
    if(isset($info['query'])) { // 解析地址里面参数 合并到vars
        parse_str($info['query'],$params);
        $vars = array_merge($params,$vars);
    }
    
    // URL组装
    $depr = C('URL_PATHINFO_DEPR');
    if($url) {
        if(0=== strpos($url,'/')) {// 定义路由
            $route      =   true;
            $url        =   substr($url,1);
            if('/' != $depr) {
                $url    =   str_replace('/',$depr,$url);
            }
        }else{
            if('/' != $depr) { // 安全替换
                $url    =   str_replace('/',$depr,$url);
            }
            // 解析分组、模块和操作
            $url        =   trim($url,$depr);
            $path       =   explode($depr,$url);
            $var        =   array();
            $var[C('VAR_ACTION')]       =   !empty($path)?array_pop($path):ACTION_NAME;
            $var[C('VAR_MODULE')]       =   !empty($path)?array_pop($path):MODULE_NAME;
            if($maps = C('URL_ACTION_MAP')) {
                if(isset($maps[strtolower($var[C('VAR_MODULE')])])) {
                    $maps    =   $maps[strtolower($var[C('VAR_MODULE')])];
                    if($action = array_search(strtolower($var[C('VAR_ACTION')]),$maps)){
                        $var[C('VAR_ACTION')] = $action;
                    }
                }
            }
            if($maps = C('URL_MODULE_MAP')) {
                if($module = array_search(strtolower($var[C('VAR_MODULE')]),$maps)){
                    $var[C('VAR_MODULE')] = $module;
                }
            }            
            if(C('URL_CASE_INSENSITIVE')) {
                $var[C('VAR_MODULE')]   =   parse_name($var[C('VAR_MODULE')]);
            }
            if(!C('APP_SUB_DOMAIN_DEPLOY') && C('APP_GROUP_LIST')) {
                if(!empty($path)) {
                    $group                  =   array_pop($path);
                    $var[C('VAR_GROUP')]    =   $group;
                }else{
                    if(GROUP_NAME != C('DEFAULT_GROUP')) {
                        $var[C('VAR_GROUP')]=   GROUP_NAME;
                    }
                }
                if(C('URL_CASE_INSENSITIVE') && isset($var[C('VAR_GROUP')])) {
                    $var[C('VAR_GROUP')]    =  strtolower($var[C('VAR_GROUP')]);
                }
            }
        }
    }

    if(C('URL_MODEL') == 0) { // 普通模式URL转换
        $url        =   __APP__.'?'.http_build_query(array_reverse($var));
        if(!empty($vars)) {
            $vars   =   urldecode(http_build_query($vars));
            $url   .=   '&'.$vars;
        }
    }else{ // PATHINFO模式或者兼容URL模式
        if(isset($route)) {
            $url    =   __APP__.'/'.rtrim($url,$depr);
        }else{
            $url    =   __APP__.'/'.implode($depr,array_reverse($var));
        }
        if(!empty($vars)) { // 添加参数
            foreach ($vars as $var => $val){
            	if (is_array($val)) $val = implode(',', $val);
                if('' !== trim($val))   $url .= $depr . $var . $depr . urlencode($val);
            }                
        }
        if($suffix) {
            $suffix   =  $suffix===true?C('URL_HTML_SUFFIX'):$suffix;
            if($pos = strpos($suffix, '|')){
                $suffix = substr($suffix, 0, $pos);
            }
            if($suffix && '/' != substr($url,-1)){
                $url  .=  '.'.ltrim($suffix,'.');
            }
        }
    }
    if(isset($anchor)){
        $url  .= '#'.$anchor;
    }
    if($domain) {
        $url   =  (is_ssl()?'https://':'http://').$domain.$url;
    }
    if($redirect) // 直接跳转URL
        redirect($url);
    else
        return $url;
}

/**
 * 渲染输出Widget
 * @param string $name Widget名称
 * @param array $data 传人的参数
 * @param boolean $return 是否返回内容 
 * @return void
 */
function W($name, $data=array(), $return=false) {
    $class      =   $name . 'Widget';
    require_cache(BASE_LIB_PATH . 'Widget/' . $class . '.class.php');
    if (!class_exists($class))
        throw_exception(L('_CLASS_NOT_EXIST_') . ':' . $class);
   
    $widget     =   Think::instance($class);
    $content    =   $widget->render($data);
    if ($return)
        return $content;
    else
        echo $content;
}

/**
 * 过滤器方法 引用传值
 * @param string $name 过滤器名称
 * @param string $content 要过滤的内容
 * @return void
 */
function filter($name, &$content) {
    $class      =   $name . 'Filter';
    require_cache(BASE_LIB_PATH . 'Filter/' . $class . '.class.php');
    $filter     =   new $class();
    $content    =   $filter->run($content);
}

/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl() {
    if(isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))){
        return true;
    }elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) {
        return true;
    }
    return false;
}

/**
 * URL重定向
 * @param string $url 重定向的URL地址
 * @param integer $time 重定向的等待时间（秒）
 * @param string $msg 重定向前的提示信息
 * @return void
 */
function redirect($url, $time=0, $msg='') {
    //多行URL地址支持
    $url        = str_replace(array("\n", "\r"), '', $url);
    if (empty($msg)) {
        $msg    = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>错误！</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Refresh" content="' . $time . ';URL=' . $url . '">
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<meta name="robots" content="index,follow" />
<meta name="googlebot" content="index,follow" />
<link rel="icon" href="/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<load href="/Public/Css/base.css" />
<style>
body{background-color:#f7f7f7;text-align:center;}
</style>
</head>

<body>
<div class="blank150"></div>

<table align="center" bgcolor="#FFFFFF" style="border-bottom:4px solid #CCC; border-top:4px solid #CCC;" border="0" cellpadding="0" cellspacing="0" width="100%">
    <tr>
      <td style="padding:20px;" align="center">
<table border="0" cellspacing="0" cellpadding="0">
  <tr>
      <td align="center" valign="top">
<div class="blank20"></div>
<font style="font-size: 25px; font-weight: bold;">错误！</font>
<div class="blank30"></div>
      <font style="font-size: 14px;">系统将在' . $time . '秒之后自动跳转到' . $url . '</font>
<div class="blank30"></div>
	  </td>
  </tr>
</table>
	  </td>
    </tr>
</table>
</body>
</html>';
    }
    else {
		$msg    = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>错误！</title>
<meta http-equiv="Refresh" content="' . $time . ';URL=' . $url . '">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<meta name="robots" content="index,follow" />
<meta name="googlebot" content="index,follow" />
<link rel="icon" href="/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/Public/Css/base.css" />
<style>
body{background-color:#f7f7f7;text-align:center;}
</style>
</head>

<body>
<div class="blank150"></div>

<table align="center" bgcolor="#FFFFFF" style="border-bottom:4px solid #CCC; border-top:4px solid #CCC;" border="0" cellpadding="0" cellspacing="0" width="100%">
    <tr>
      <td style="padding:20px;" align="center">
<table border="0" cellspacing="0" cellpadding="0">
  <tr>
      <td align="center" valign="top">
<div class="blank20"></div>
<font style="font-size: 25px; font-weight: bold;">错误！</font>
<div class="blank30"></div>
      <font style="font-size: 14px;">' . $msg . '<br /><br />系统将在' . $time . '秒之后自动跳转到' . $url . '</font>
<div class="blank30"></div>
	  </td>
  </tr>
</table>
	  </td>
    </tr>
</table>
</body>
</html>';
    }
    
    if (!headers_sent()) {
        // redirect
        if (0 === $time) {
            header('Location: ' . $url);
        } else {
            header("refresh:{$time};url={$url}");
            echo($msg);
        }
        exit();
    } else {
        $str    = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>错误！</title>
<meta http-equiv="Refresh" content="' . $time . ';URL=' . $url . '">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<meta name="robots" content="index,follow" />
<meta name="googlebot" content="index,follow" />
<link rel="icon" href="/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/Public/Css/base.css" />
<style>
body{background-color:#f7f7f7;text-align:center;}
</style>
</head>

<body>
<div class="blank150"></div>

<table align="center" bgcolor="#FFFFFF" style="border-bottom:4px solid #CCC; border-top:4px solid #CCC;" border="0" cellpadding="0" cellspacing="0" width="100%">
    <tr>
      <td style="padding:20px;" align="center">
<table border="0" cellspacing="0" cellpadding="0">
  <tr>
      <td align="center" valign="top">
<div class="blank20"></div>
<font style="font-size: 25px; font-weight: bold;">错误！</font>
<div class="blank30"></div>
      <font style="font-size: 14px;">' . $msg . '<br /><br />系统将在' . $time . '秒之后自动跳转到' . $url . '</font>
<div class="blank30"></div>
	  </td>
  </tr>
</table>
	  </td>
    </tr>
</table>
</body>
</html>';
        exit($str);
    }
}

/**
 * 缓存管理
 * @param mixed $name 缓存名称，如果为数组表示进行缓存设置
 * @param mixed $value 缓存值
 * @param mixed $options 缓存参数
 * @return mixed
 */
function S($name,$value='',$options=null) {
    static $cache   =   '';
    if(is_array($options)){
        // 缓存操作的同时初始化
        $type       =   isset($options['type'])?$options['type']:'';
        $cache      =   Cache::getInstance($type,$options);
    }elseif(is_array($name)) { // 缓存初始化
        $type       =   isset($name['type'])?$name['type']:'';
        $cache      =   Cache::getInstance($type,$name);
        return $cache;
    }elseif(empty($cache)) { // 自动初始化
        $cache      =   Cache::getInstance();
    }
    if(''=== $value){ // 获取缓存
        return $cache->get($name);
    }elseif(is_null($value)) { // 删除缓存
        return $cache->rm($name);
    }else { // 缓存数据
        $expire     =   is_numeric($options)?$options:NULL;
        return $cache->set($name, $value, $expire);
    }
}
// S方法的别名 已经废除 不再建议使用
function cache($name,$value='',$options=null){
    return S($name,$value,$options);
}

/**
 * 快速文件数据读取和保存 针对简单类型数据 字符串、数组
 * @param string $name 缓存名称
 * @param mixed $value 缓存值
 * @param string $path 缓存路径
 * @return mixed
 */
function F($name, $value='', $path=DATA_PATH) {
    static $_cache  = array();
    $filename       = $path . $name . '.php';
    if ('' !== $value) {
        if (is_null($value)) {
            // 删除缓存
            return false !== strpos($name,'*')?array_map("unlink", glob($filename)):unlink($filename);
        } else {
            // 缓存数据
            $dir            =   dirname($filename);
            // 目录不存在则创建
            if (!is_dir($dir))
                mkdir($dir,0755,true);
            $_cache[$name]  =   $value;
            return file_put_contents($filename, strip_whitespace("<?php\treturn " . var_export($value, true) . ";?>"));
        }
    }
    if (isset($_cache[$name]))
        return $_cache[$name];
    // 获取缓存数据
    if (is_file($filename)) {
        $value          =   include $filename;
        $_cache[$name]  =   $value;
    } else {
        $value          =   false;
    }
    return $value;
}

/**
 * 取得对象实例 支持调用类的静态方法
 * @param string $name 类名
 * @param string $method 方法名，如果为空则返回实例化对象
 * @param array $args 调用参数
 * @return object
 */
function get_instance_of($name, $method='', $args=array()) {
    static $_instance = array();
    $identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args);
    if (!isset($_instance[$identify])) {
        if (class_exists($name)) {
            $o = new $name();
            if (method_exists($o, $method)) {
                if (!empty($args)) {
                    $_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
                } else {
                    $_instance[$identify] = $o->$method();
                }
            }
            else
                $_instance[$identify] = $o;
        }
        else
            halt(L('_CLASS_NOT_EXIST_') . ':' . $name);
    }
    return $_instance[$identify];
}

/**
 * 根据PHP各种类型变量生成唯一标识号
 * @param mixed $mix 变量
 * @return string
 */
function to_guid_string($mix) {
    if (is_object($mix) && function_exists('spl_object_hash')) {
        return spl_object_hash($mix);
    } elseif (is_resource($mix)) {
        $mix = get_resource_type($mix) . strval($mix);
    } else {
        $mix = serialize($mix);
    }
    return md5($mix);
}

/**
 * XML编码
 * @param mixed $data 数据
 * @param string $encoding 数据编码
 * @param string $root 根节点名
 * @return string
 */
function xml_encode($data, $encoding='utf-8', $root='shagua') {
    $xml    = '<?xml version="1.0" encoding="' . $encoding . '"?>';
    $xml   .= '<' . $root . '>';
    $xml   .= data_to_xml($data);
    $xml   .= '</' . $root . '>';
    return $xml;
}

/**
 * 数据XML编码
 * @param mixed $data 数据
 * @return string
 */
function data_to_xml($data) {
    $xml = '';
    foreach ($data as $key => $val) {
        is_numeric($key) && $key = "item id=\"$key\"";
        $xml    .=  "<$key>";
        $xml    .=  ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val;
        list($key, ) = explode(' ', $key);
        $xml    .=  "</$key>";
    }
    return $xml;
}

/**
 * session管理函数
 * @param string|array $name session名称 如果为数组则表示进行session设置
 * @param mixed $value session值
 * @return mixed
 */
function session($name,$value='') {
    $prefix   =  C('SESSION_PREFIX');
    if(is_array($name)) { // session初始化 在session_start 之前调用
        if(isset($name['prefix'])) C('SESSION_PREFIX',$name['prefix']);
        if(C('VAR_SESSION_ID') && isset($_REQUEST[C('VAR_SESSION_ID')])){
            session_id($_REQUEST[C('VAR_SESSION_ID')]);
        }elseif(isset($name['id'])) {
            session_id($name['id']);
        }
        ini_set('session.auto_start', 0);
        if(isset($name['name']))            session_name($name['name']);
        if(isset($name['path']))            session_save_path($name['path']);
        if(isset($name['domain']))          ini_set('session.cookie_domain', $name['domain']);
        if(isset($name['expire']))          ini_set('session.gc_maxlifetime', $name['expire']);
        if(isset($name['use_trans_sid']))   ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0);
        if(isset($name['use_cookies']))     ini_set('session.use_cookies', $name['use_cookies']?1:0);
        if(isset($name['cache_limiter']))   session_cache_limiter($name['cache_limiter']);
        if(isset($name['cache_expire']))    session_cache_expire($name['cache_expire']);
        if(isset($name['type']))            C('SESSION_TYPE',$name['type']);
        if(C('SESSION_TYPE')) { // 读取session驱动
            $class      = 'Session'. ucwords(strtolower(C('SESSION_TYPE')));
            // 检查驱动类
            if(require_cache(EXTEND_PATH.'Driver/Session/'.$class.'.class.php')) {
                $hander = new $class();
                $hander->execute();
            }else {
                // 类没有定义
                throw_exception(L('_CLASS_NOT_EXIST_').': ' . $class);
            }
        }
        // 启动session
        if(C('SESSION_AUTO_START'))  session_start();
    }elseif('' === $value){ 
        if(0===strpos($name,'[')) { // session 操作
            if('[pause]'==$name){ // 暂停session
                session_write_close();
            }elseif('[start]'==$name){ // 启动session
                session_start();
            }elseif('[destroy]'==$name){ // 销毁session
                $_SESSION =  array();
                session_unset();
                session_destroy();
            }elseif('[regenerate]'==$name){ // 重新生成id
                session_regenerate_id();
            }
        }elseif(0===strpos($name,'?')){ // 检查session
            $name   =  substr($name,1);
            if($prefix) {
                return isset($_SESSION[$prefix][$name]);
            }else{
                return isset($_SESSION[$name]);
            }
        }elseif(is_null($name)){ // 清空session
            if($prefix) {
                unset($_SESSION[$prefix]);
            }else{
                $_SESSION = array();
            }
        }elseif($prefix){ // 获取session
            return isset($_SESSION[$prefix][$name])?$_SESSION[$prefix][$name]:null;
        }else{
            return isset($_SESSION[$name])?$_SESSION[$name]:null;
        }
    }elseif(is_null($value)){ // 删除session
        if($prefix){
            unset($_SESSION[$prefix][$name]);
        }else{
            unset($_SESSION[$name]);
        }
    }else{ // 设置session
        if($prefix){
            if (!(isset($_SESSION[$prefix]) && is_array($_SESSION[$prefix]))) {
                $_SESSION[$prefix] = array();
            }
            $_SESSION[$prefix][$name]   =  $value;
        }else{
            $_SESSION[$name]  =  $value;
        }
    }
}

/**
 * Cookie 设置、获取、删除
 * @param string $name cookie名称
 * @param mixed $value cookie值
 * @param mixed $options cookie参数
 * @return mixed
 */
function cookie($name, $value='', $option=null) {
    // 默认设置
    $config = array(
        'prefix'    =>  C('COOKIE_PREFIX'), // cookie 名称前缀
        'expire'    =>  C('COOKIE_EXPIRE'), // cookie 保存时间
        'path'      =>  C('COOKIE_PATH'), // cookie 保存路径
        'domain'    =>  C('COOKIE_DOMAIN'), // cookie 有效域名
    );
    // 参数设置(会覆盖黙认设置)
    if (!is_null($option)) {
        if (is_numeric($option))
            $option = array('expire' => $option);
        elseif (is_string($option))
            parse_str($option, $option);
        $config     = array_merge($config, array_change_key_case($option));
    }
    // 清除指定前缀的所有cookie
    if (is_null($name)) {
        if (empty($_COOKIE))
            return;
        // 要删除的cookie前缀，不指定则删除config设置的指定前缀
        $prefix = empty($value) ? $config['prefix'] : $value;
        if (!empty($prefix)) {// 如果前缀为空字符串将不作处理直接返回
            foreach ($_COOKIE as $key => $val) {
                if (0 === stripos($key, $prefix)) {
                    setcookie($key, '', time() - 3600, $config['path'], $config['domain']);
                    unset($_COOKIE[$key]);
                }
            }
        }
        return;
    }
    $name = $config['prefix'] . $name;
    if ('' === $value) {
        if(isset($_COOKIE[$name])){
            $value =    $_COOKIE[$name];
            if(0===strpos($value,'shagua:')){
                $value  =   substr($value,6);
                return array_map('urldecode',json_decode(MAGIC_QUOTES_GPC?stripslashes($value):$value,true));
            }else{
                return $value;
            }
        }else{
            return null;
        }
    } else {
        if (is_null($value)) {
            setcookie($name, '', time() - 3600, $config['path'], $config['domain']);
            unset($_COOKIE[$name]); // 删除指定cookie
        } else {
            // 设置cookie
            if(is_array($value)){
                $value  = 'shagua:'.json_encode(array_map('urlencode',$value));
            }
            $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0;
            setcookie($name, $value, $expire, $config['path'], $config['domain']);
            $_COOKIE[$name] = $value;
        }
    }
}

/**
 * 加载动态扩展文件
 * @return void
 */
function load_ext_file() {
    // 加载自定义外部文件
    if(C('LOAD_EXT_FILE')) {
        $files      =  explode(',',C('LOAD_EXT_FILE'));
        foreach ($files as $file){
            $file   = COMMON_PATH.$file.'.php';
            if(is_file($file)) include $file;
        }
    }
    // 加载自定义的动态配置文件
    if(C('LOAD_EXT_CONFIG')) {
        $configs    =  C('LOAD_EXT_CONFIG');
        if(is_string($configs)) $configs =  explode(',',$configs);
        foreach ($configs as $key=>$config){
            $file   = CONF_PATH.$config.'.php';
            if(is_file($file)) {
                is_numeric($key)?C(include $file):C($key,include $file);
            }
        }
    }
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0) {
	$type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 发送HTTP状态
 * @param integer $code 状态码
 * @return void
 */
function send_http_status($code) {
    static $_status = array(
        // Success 2xx
        200 => 'OK',
        // Redirection 3xx
        301 => 'Moved Permanently',
        302 => 'Moved Temporarily ',  // 1.1
        // Client Error 4xx
        400 => 'Bad Request',
        403 => 'Forbidden',
        404 => 'Not Found',
        // Server Error 5xx
        500 => 'Internal Server Error',
        503 => 'Service Unavailable',
    );
    if(isset($_status[$code])) {
        header('HTTP/1.1 '.$code.' '.$_status[$code]);
        // 确保FastCGI模式下正常
        header('Status:'.$code.' '.$_status[$code]);
    }
}

// 过滤表单中的表达式
function filter_exp(&$value){
    if (in_array(strtolower($value),array('exp','or'))){
        $value .= ' ';
    }
}

// 引入语言包
function require_lang(){
	require_once('Language/zh_cn/lang.php');
}

//输出调试信息，函数调用过程
function show_debug_info()
{
	$bt = debug_backtrace();
	foreach ($bt AS $v)
	{
		echo $v['file'] . ' on line ' . $v['line'] . "<br>";
		echo $v['function'] . "<br><br>";
	}
}

//获取当前方法的调用者方法名
function get_latest_caller()
{
	$bt = debug_backtrace();
	if (isset($bt[2]))
	{
		return $bt[2]['function'];
	}
	return null;
}

function log_file($str, $file_name = '', $daily_write = false, $user_id = 0)
{
	$sess_user_id = intval(session('user_id'));
	if ( $user_id == 0 || ($user_id == $sess_user_id) )
	{
		$file_path = 'logs/';
		$file_path .= $file_name ? $file_name . ($daily_write ? '.' . date('Y-m-d', time()) : '') . '.log' : 'event.' . date('Y-m-d', time()) . '.log';
		$file = fopen($file_path, 'a');
		fwrite($file, date('Y-m-d H:i:s', time()) . "\n" . $str . "\n");
		fclose($file);
	}
}

function utf8_strlen($str)
{
	$count = 0;
	for ($i = 0; $i < strlen($str); $i++)
	{
		$value = ord($str[$i]);
		if($value > 127)
		{
			$count++;
			if($value >= 192 && $value <= 223) $i++;
			elseif($value >= 224 && $value <= 239) $i = $i + 2;
			elseif($value >= 240 && $value <= 247) $i = $i + 3;
		}
		$count++;
	}
	return $count;
}

/**
 * 调用淘宝API获取IP来源（省市ID）
 * 
 * $ip	ip地址
 * return	$arr	两个元素，0表示省份ID，1表示城市ID
 */
function getIPSource($ip)
{
	if ($ip == '127.0.0.1')
	{
		$ip = '115.29.231.179';
	}
	$url = 'http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip;
	$ip = json_decode(file_get_contents($url));

	if( (string)$ip->code == '1' )
	{
		return false;
	}

	$data = (array)$ip->data;
	$province_name = $data['region'];
	$city_name = $data['city'];
	$Province = M('Address_province');
	$City = M('Address_city');

	$row_province = $Province->where('province_name = "' . $province_name . '"')->limit(0, 1)->select();
	//如果是直辖市 只返回省份ID，城市ID为0
	if ($city_name == '上海市' || $city_name == '北京市' || $city_name == '天津市' || $city_name == '重庆市')
	{
		return array('province_id' => $row_province[0]['province_id'], 'city_id' => 0);
	}

	//否则根据城市名称查询城市ID并返回 省份ID和城市ID
	$row_city = $City->where('city_name = "' . $city_name . '"')->limit(0, 1)->select();
	return array('province_id' => $row_province[0]['province_id'], 'city_id' => $row_city[0]['city_id'], 'province_name' => $province_name, 'city_name' => $city_name);
}

function arrayToString($data)
{
	$str = '';
	foreach($data as $key => $val)
	{
		$str .= "&$key=$val";
	}
	return $str;
}

function select_sort_asc($arr, $field)
{
	$count = count($arr);
	for ($i = 0; $i < $count; $i ++)
	{
		$min = $i;
		for ($j = $i + 1; $j < $count; $j ++)
		{
			if ($arr[$j][$field] < $arr[$min][$field])
			{
				$temp = $arr[$j];
				$arr[$j] = $arr[$min];
				$arr[$min] = $temp;
			}
		}
	}

	return $arr;
}

function select_sort_desc($arr, $field)
{
	$count = count($arr);
	for ($i = 0; $i < $count; $i ++)
	{
		$max = $i;
		for ($j = $i + 1; $j < $count; $j ++)
		{
			if ($arr[$j][$field] > $arr[$max][$field])
			{
				$temp = $arr[$j];
				$arr[$j] = $arr[$max];
				$arr[$max] = $temp;
			}
		}
	}

	return $arr;
}

//获取二维码
function get_qr_code()
{
	//判断分销是否开启
	if (!FenxiaoModel::isFenxiaoOpen())
	{
		return false;
	}

	$user_id = intval(session('user_id'));
	if (!$user_id)
	{
		return false;
	}
	$user_obj = new UserModel($user_id);
	$user_info = $user_obj->getUserInfo('qr_code, openid, qr_code_expire_time');
	if ((!$user_info || $user_info['qr_code_expire_time'] >= time() || !$user_info['openid'])  && filesize( APP_PATH . $user_info['qr_code']) > 1024)
	{
log_file('2' . json_encode($user_info), 'qrcode');
#log_file('2' . file_exists(APP_PATH . $user_info['qr_code']) ? 1 : 0, 'qrcode');
		//若用户不存在或用户已生成过二维码，或用户不是微信用户，退出
		return false;
	}

	//文件名和文件路径
	$savePath = 'Uploads/' . date('Y-m') . '/' . date('Y-m-d') . '/';
	$saveFile = $savePath . $user_id . '.jpg';
	$qr_code = '/' . $saveFile;
	$savePath = APP_PATH . $savePath;

	//确认保存路径，没有则创建
	if(!is_dir($savePath))
	{
		if(!@mkdir($savePath, 0700, true))
		{
			return array('status' => 0, 'msg' => '上传目录创建失败！');
		}
	}

	//获取二维码
	$appid = C('APPID');
	$secret = C('APPSECRET');
	vendor('Wxin.WeiXin');
	$access_token = WxApi::getAccessToken($appid, $secret);
	$weixin_obj = new WxApi($access_token);
	$arr = array(
		'expire_seconds'	=> 604800,
		'action_name'	=> 'QR_SCENE',
		'action_info'	=> array(
			'sence'	=> array(
				'scene_id'	=> 123456789
			)
		),
	);
	$result = $weixin_obj->generate_qr_code($arr);
	$ticket = $result['ticket'];
	$link = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($ticket);
	//获取图片
$file = put_file_from_url_content($link, $saveFile);
	/*$pic = file_get_contents($link);
	//保存图片
	$file = null;
	while (!$file)
	{
		$file = file_put_contents($saveFile, $pic);
	}*/

	//保存文件路径和ticket到数据库
	$arr = array(
		'ticket'		=> $ticket,
		'qr_code'		=> $qr_code,
		'qr_code_expire_time'	=> time() + 86400 * 7,
	);
	$user_obj->setUserInfo($arr);
	$user_obj->saveUserInfo();

	return $file;
}

//根据openid获取关注时推送的图片
function get_push_img($openid)
{
	//文件名和文件路径
	$savePath = 'Uploads/water_img/' . date('Y-m') . '/' . date('Y-m-d') . '/';
	$file_path = APP_PATH . $savePath . time() . randLenString(6,1) . '.png';
	$file_path1 = APP_PATH .$savePath . time() . randLenString(6,1) . '.png';
	
	//确认保存路径，没有则创建
	if(!is_dir($savePath))
	{
		if(!@mkdir($savePath, 0700, true))
		{
			return array('status' => 0, 'msg' => '上传目录创建失败！');
		}
	}

	import('ORG.Util.Image');
	$Image = new Image();
	$user_info = get_headimgurl($openid);
	$headimgurl = $user_info['headimgurl'];
$last_char = substr($headimgurl, -1, 1);
$suffix = $last_char == '/' ? '/132' : '132';
$headimgurl = substr($headimgurl, 0, -1) . $suffix;
	#$pic = @file_get_contents($headimgurl);
	#$pic = @http_get_data($headimgurl);
put_file_from_url_content($headimgurl, $file_path);
	#@file_put_contents($file_path, $pic);
	#$Image->thumb($file_path, $file_path1, '', 150, 150);
	$water_img = $file_path;
	#$water_img = $headimgurl;

	/***** 图片加水印 开始 *****/
	// 水印图片
	$base_path = $savePath . 'subscribe_push_' . time() . randLenString(6,1) . '.jpg';
	$big_img = APP_PATH . $base_path;
	copy('Public/Images/common/subscribe_push.jpg', $big_img);
	$return_path = '/' . $base_path;

	// 水印透明度
	$alpha = 100;

	//水印位置
	$position = 6;

	//加水印
	$success = $Image->water($big_img, $water_img, '', $alpha, $position);

	#echo $headimgurl . "<br>";
	#echo '<img src="' . $file_path .'">' . "<br>";
	#echo '<img src="' . $file_path1 .'">' . "<br>";
	#echo '<img src="' . $return_path .'">' . "<br>";
	#echo $file_path . "<br>";
	#echo $file_path1 . "<br>";
	#echo $return_path . "<br>";

	$return_arr = array(
		'nickname'		=> $user_info['nickname'],
		'province'		=> $user_info['province'],
		'city'			=> $user_info['city'],
		'sex'			=> $user_info['sex'],
		'headimgurl'		=> $user_info['headimgurl'],
		'push_img'		=> $return_path,
	);
#log_file('return_arr = ' . json_encode($return_arr), 'subscribe');
	return $return_arr;
}


//根据openid获取用户微信头像
function get_headimgurl($openid)
{
	//查询user表，若user表中已存在该用户记录，直接取头像，否则调用微信接口获取
	$user_obj = new UserModel();
	$user_info = $user_obj->field('headimgurl, nickname, province, city')->where('openid = "' . $openid . '"')->find();
	$headimgurl = $user_info['headimgurl'];
	if (!$headimgurl)
	{
		//调用接口获取
		$appid = C('APPID');
		$secret = C('APPSECRET');
		require('frame/Extend/Vendor/Wxin/WeiXin.php');
		$access_token = (WxApi::getAccessToken($appid, $secret));
		$wxapi_obj = new WxApi($access_token);
		$user_info = $wxapi_obj->user_info($openid);
log_file('2 user_info = ' . json_encode($user_info), 'subscribe');
	}
	/*if (!$headimgurl)
	{
		//调用接口获取
		$appid = C('APPID');
		$secret = C('APPSECRET');
		require('frame/Extend/Vendor/Wxin/WeiXin.php');
		$access_token = (WxApi::getAccessToken($appid, $secret));
		$wxapi_obj = new WxApi($access_token);
		$next_openid = '';
		while (!$headimgurl)
		{
			$arr = array(
				'next_openid'	=> $next_openid
			);
			$user_list = $wxapi_obj->user_get();
			$next_openid = $user_list['next_openid'];
			#echo $user_list['next_openid'] . "<br>";
			#echo "<pre>";
			#print_r($user_list);
			foreach ($user_list['data']['openid'] AS $k => $v)
			{
				if ($v == $openid)
				{
					$user_info = $wxapi_obj->user_info($v);
					return $user_info;
					#var_dump($user_info);
					#$headimgurl = $user_info['headimgurl'];
					#break;
				}
			}
		}
	}*/

	#echo $headimgurl;
	return $user_info;
}


/**
 * 异步将远程链接上的内容(图片或内容)写到本地
 * 
 * @param unknown $url
 *            远程地址
 * @param unknown $saveName
 *            保存在服务器上的文件名
 * @param unknown $path
 *            保存路径
 * @return boolean
 */
function put_file_from_url_content($url, $filename)
{
	// 设置运行时间为无限制
	set_time_limit ( 0 );

	$url = trim ( $url );
	$curl = curl_init ();
	// 设置你需要抓取的URL
	curl_setopt ( $curl, CURLOPT_URL, $url );
	// 设置header
	curl_setopt ( $curl, CURLOPT_HEADER, 0 );
	// 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
	curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
     curl_setopt($curl, CURLOPT_NOBODY, 0); 
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	// 运行cURL，请求网页
	$file = curl_exec ( $curl );
	// 关闭URL请求
	curl_close ( $curl );
	// 将文件写入获得的数据
	$write = @fopen ( $filename, "w+" );
	#dump($write);
	#dump($url);
	#dump($filename);die;
	if ($write == false) {
		return false;
	}
	if (fwrite ( $write, $file ) == false) {
		return false;
	}
	if (fclose ( $write ) == false) {
		return false;
	}
}

/**
 * 获取sign
 * @author 姜伟
 * @param array $params 请求参数列表
 * @return string sign
 * @todo 排序，组成请求字符串后，连接key进行MD5加密，返回
 */
function generateSign($data)
{
	ksort($data);

	$sign = '';
	foreach($data as $key => $val)
	{
		if($key != 'token')
		{
			$sign .= "&$key=$val";
		}
	}

	$api_obj = new ApiModel();
	$sign = md5(substr($sign, 1) . $api_obj->key);
	return $sign;
}

function delFileUnderDir($dirName)
{
	$handle = opendir($dirName);
	if ($handle)
   	{
		while (false !== ($item = readdir($handle)))
		{
			if ( $item != "." && $item != ".." )
			{
				#echo "$dirName/$item<br>";
				if (is_dir("$dirName/$item"))
				{
					delFileUnderDir("$dirName/$item");
				}
				else
				{
					if(unlink("$dirName/$item"))
					{
						#echo "成功删除文件： $dirName/$item<br />n";
					}
				}
			}
		}
		closedir($handle);
	}
}

function deldir($dir)
{
	//先删除目录下的文件：
	$dh = opendir($dir);
	while ($file = readdir($dh))
	{
		if($file != "." && $file != "..")
		{
			$fullpath = $dir . "/" . $file;
			if(!is_dir($fullpath))
			{
				unlink($fullpath);
			}
			else
			{
				deldir($fullpath);
			}
		}
	}

	closedir($dh);
	//删除当前文件夹：
	/*if(rmdir($dir))
	{
		return true;
	}
	else
	{
		return false;
	}*/
}

function cur_merchant_id($cur_merchant_id = 0)
{
	if ($cur_merchant_id)
	{
		session('cur_merchant_id', $cur_merchant_id);
	}

	$merchant_id = intval(session('cur_merchant_id'));
	return $merchant_id ? $merchant_id : 99194;
}

function cur_user_id($cur_user_id = 0)
{
	if ($cur_user_id)
	{
		session('user_id', $cur_user_id);
	}

	$user_id = intval(session('user_id'));
	return $user_id ? $user_id : 99195;
}

function api_echo($str)
{
	if (isset($_GET['debug']))
	{
		echo $str . "<br>";
	}
}

function get_image_path($file)
{
	$file_path = APP_PATH . $file;
	$file_exists = file_exists($file_path);
	$file_path = $file_exists ? $file : '';
	return $file_path;
}

//发送邮件
function send_email($title, $body = '', $account = '', $send_mail = false)
{
	if (!$send_mail)
	{
		log_file($title . "\n" .  $body, 'mail');
	}
	else
	{
		$account = $account ? $account : '396162022@qq.com';
		return EmailModel::sendEmail($account, date('i:s', time()) . ': ' . $title, $body);
	}
}

//写操作日志
function add_log($tb_id, $op_type, $tb_name, $sql)
{
	$user_id = intval(session('user_id'));
	$user_obj = new UserModel($user_id);
	$user_info = $user_obj->getUserInfo('role_type, realname');
	if ($user_info['role_type'] == 1 && $tb_name != 'tp_logs')
	{
		$logs_obj = new LogsModel();
		$result = $logs_obj->query('SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = "' . $tb_name . '" AND TABLE_SCHEMA = "wallet"');
		$mark = mbSubStr($result[0]['TABLE_COMMENT'], strlen($result[0]['TABLE_COMMENT']) / 3 - 1, '');
		$mark = get_op_tpye($op_type) . $mark;
		$arr = array(
			'tb_id'			=> $tb_id,
			'op_user_id'	=> $user_id,
			'ip'			=> get_client_ip(),
			'op_time'		=> time(),
			'op_type'		=> $op_type,
			'tb_name'		=> $tb_name,
			'mark'			=> $mark,
			'sql'			=> $sql,
			'linkman'		=> $user_info['realname'],
		);
		$logs_obj->addLogs($arr);
	}
}

function get_op_tpye_list()
{
	return array(
		'1'	=> '新增',
		'2'	=> '修改',
		'3'	=> '删除',
	);
}

function get_op_tpye($op_type)
{
	$type_list = get_op_tpye_list();
	return $type_list[$op_type];
}

//首字母大写改下划线
function cc_format($name)
{
	$temp_array = array();
	for($i=0;$i<strlen($name);$i++)
	{
		$ascii_code = ord($name[$i]);
		if($ascii_code >= 65 && $ascii_code <= 90)
		{
			if($i == 0)
			{
				$temp_array[] = chr($ascii_code + 32);
			}
			else
			{
				$temp_array[] = '_'.chr($ascii_code + 32);
			}
		}
		else
		{
			$temp_array[] = $name[$i];
		}
	}
	return implode('',$temp_array);
}

//生成excel报错信息，demo: wallet->AcpUser->import_user
function generateExcelError($line, $data, $msg)
{
	$new_line = "\n";
	$str = '第' . $line . '行' . $msg . $new_line;
	$str .= '数据内容：' . $new_line;
	foreach ($data AS $k => $v)
	{
		$str .= $v;
		$str .= $k == (count($data) - 1) ? '。' : '，';
	}

	return $str . $new_line . $new_line;
}

//导出txt文件，demo: wallet->AcpUser->import_user
function exportTxt($contents, $filename = '')
{
	$filename = ($filename ? $filename : time()) . '.txt';
	header("Content-Type: application/octet-stream");   
	header('Content-Disposition: attachment; filename="' . $filename . '"');
	header('Content-Type: application/octet-stream; name="' . $filename . '"');

	echo $contents;
	exit;
}

function upload_weixin_img($img_path)
{
	Vendor('Wxin.WeiXin');
	$appid = C('appid');
	$secret = C('appsecret');
	$wx_obj = new WxApi($appid, $secret);
	$access_token = WxApi::getAccessToken($appid, $secret);
#dump($access_token);
	$file = APP_PATH . $img_path;
	$result = $wx_obj->uploadMedia($access_token, $file, 'image', false);
	log_file('result = ' . $result, 'kf_push');
	$result = json_decode($result, true);

	return $result['media_id'];
}

function get_media_id($id)
{
	Vendor('Wxin.WeiXin');
	$appid = C('appid');
	$secret = C('appsecret');
	$wx_obj = new WxApi($appid, $secret);
	$access_token = WxApi::getAccessToken($appid, $secret);
#dump($access_token);
	$kw_obj = new WxKwReplyModel($id);
	$info = $kw_obj->getWxKwReplyInfo('wx_kw_reply_id = ' . $id, 'media_id, img_url, expire_time, media_url');
	#log_file(json_encode($info), 'ca', true);
	$media_id = $info['media_id'];
	$media_url = $info['media_url'];
	$img_url = $info['img_url'];
	$expire_time = $info['expire_time'];
	if (!$media_id || !$media_url || $expire_time < time())
	{
		$file = APP_PATH . $img_url;
		$result = $wx_obj->uploadMedia($access_token, $file, 'image', false);
#log_file('result = ' . $result, 'kf_push');
		$result = json_decode($result, true);
		$media_id = $result['media_id'];

		//保存到数据库
		$arr = array(
			'media_id'		=> $media_id,
			'media_url'		=> $result['url'],
			'expire_time'	=> time() + 86400 * 3 - 600,
		);
		$kw_obj->editWxKwReply($arr);
	}

	return $media_id;
}

